﻿using AutoMapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;

namespace Songhay.BiggestBox.Desktop.Modules.ODataWeather.ModelContext
{
    using OData;
    using ViewModels;

    public static class CambridgeWeatherContext
    {
        static CambridgeWeatherContext()
        {
            uri = new Uri("http://odata.pyslet.org/weather/", UriKind.Absolute);
        }

        public static CambridgeWeather GetContext()
        {
            return new CambridgeWeather(uri);
        }

        public static async Task<IEnumerable<DataPointViewModel>> LoadDataPointsAsync()
        {
            var context = CambridgeWeatherContext.GetContext();

            var query = (DataServiceQuery)context.DataPoints
                .Where(i => i.TimePoint.Year == DateTime.Now.Year)
                .Where(i => i.TimePoint.Month == DateTime.Now.Month)
                .Select(i =>
                new
                {
                    DewPoint = i.DewPoint,
                    Humidity = i.Humidity,
                    Pressure = i.Pressure,
                    Rain = i.Rain,
                    Sun = i.Sun,
                    Temperature = i.Temperature,
                    TimePoint = i.TimePoint,
                    WindDirection = i.WindDirection,
                    WindSpeed = i.WindSpeed,
                    WindSpeedMax = i.WindSpeedMax
                });

            var result = await Task<IEnumerable>.Factory.FromAsync(query.BeginExecute, query.EndExecute, null);
            var boxList = result.OfType<object>().ToList();
            var data = boxList
                .Select(Mapper.DynamicMap<DataPointViewModel>)
                .ToList();

            return data;
        }

        static readonly Uri uri;
    }
}
